<template>
    <div class="page">
        <AdminLayout
            :left-fixed="true"
            no-sel-message="请选择公司或部门再进行操作~"
            ref="adminLayout"
        >
            <template #left>
                <div v-show="isShowTree" style="height: 100%;" >
                    <SideTree
                        v-if="!props.currentType && !similarityFlag" 
                        ref="sideTreeRef"
                        @setShowTree="setShowTree"
                        @searchAllData="searchAllData"
                        @selectTree="selectTree"
                        @SuccessfuCallbackFn="SuccessfuCallbackFn"
                        @handNameFn="handNameFn" 
                        @createFolder="parentChang" 
                        @handleTreeDelete="handleTreeDelete" 
                        @handleTreeMove="handleTreeMove" />
                </div> 
            </template>
    <main class="page admin-page page-container">
        <div class="page-title">
            <div class="left">
                <div class="name">罗凤鸣</div>
                <div class="routes">
                    <div class="bread-crumb scroll-style">
                        <div v-for="(v, i) in breadCrumb" @click="changeCrumb(v, i)" :key="i" class="bread-crumb-item">
                            <span class="bread-crumb-line" v-if="i != 0">/</span>
                            <span class="bread-crumb-word">{{ v.title }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="search-box">
                <a-input-search
                    width="460"
                    placeholder="请输入"
                    enter-button
                />
            </div>
            <div class="right-upload"
                @mouseenter="handleEnter"
                @mouseleave="handleLeave">
                <a-button class="upload-select">
                    <i class="folder-upload" />
                    <p>上传</p>
                </a-button>
            </div>
        </div>
        
        <!-- main flex -->
        <div class="content-wrapper">
            <!-- main -->
            <div class="condition-filter-box admin-page-filter-box">
                <div class="header-filter-wrapper">
                    <div class="filter-wrapper">
                        <!-- 类型选择 -->
                        <div class="filter-block">
                            <label>类型</label>
                            <a-select
                            ref="select"
                            v-model:value="tabPosition"
                            style="width: 120px"
                            @change="tabChangeTypeFn"
                            >
                                <a-select-option 
                                v-for="item in mainTypeOption" 
                                :value="item.type"
                                :key="item">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                        </div>
                        <!-- 标签选择 -->
                        <div class="filter-block">
                            <label>标签</label>
                            <a-select
                            ref="select"
                            v-model:value="tabPosition"
                            style="width: 120px"
                            @change="tabChangeTypeFn"
                            >
                                <a-select-option 
                                v-for="item in mainTypeOption" 
                                :value="item.type"
                                :key="item">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                        </div>
                        <!-- 排序选择 -->
                        <div class="filter-block">
                            <label>排序</label>
                            <a-select
                            ref="select"
                            v-model:value="filterObj['ifDesc']['activeId']"
                            style="width: 120px"
                            @change="selectDesc"
                            >
                                <a-select-option 
                                v-for="item in filterObj['ifDesc']['val']" 
                                :value="item.id"
                                :key="item">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                        </div>
                        <!-- 时间选择 -->
                        <div class="filter-block">
                            <label>时间</label>
                            <a-range-picker
                            v-model:value="dateVal" 
                            @change="dateFnPre" 
                            format="YYYY-MM-DD"
                            valueFormat="YYYY-MM-DD" 
                            allowClear/>
                        </div>
                    </div>
                    <div class="show-child-wrapper">
                        <a-switch size="small" v-model:checked="showChild" />
                        <label>显示子文件夹内容</label>
                    </div>
                </div>

                <!-- 列表 -->
                <div class="list page_auto_list"
                    :class="{ 'page_auto_list-active': breadCrumb.length > 1, 'page_auto_list-criteria': isCriteria && filterFlag1, 'page_auto_list-no-criteria': isCriteria && !filterFlag1, 'showFilterClasscolumns': filterFlag1 && !props.currentType }"
                    id="admin-page" ref="rollContainer">
                    <div class="init_data_main">
                        <div class="label-tips-block">
                            <a-checkbox v-model:checked="state.checkAll">子文件夹（5）</a-checkbox>
                            <DownOutlined />
                        </div>
                        <!-- 文件夹 -->
                        <a-checkbox-group v-model:value="state.checkedList">
                            <ul>
                                <li v-for="(item, index) in initDataArr"
                                    :class="[ state.selectList.join(',').match(item.media_resource_id) ? 'active': '', item.main_type != 7 ? 'hiddenBox': '' ]"
                                    @mouseover.stop="handShowCheck(item)" 
                                    :key="index">
                                    <!-- 复选框 -->
                                    <span v-if="item.main_type != 11" @click.stop class="checkbox-section"
                                        v-show="state.selectList.join(',').match(item.media_resource_id) || checkBoxItem == item.media_resource_id">
                                        <a-checkbox :value="item" :key="item.media_resource_id"
                                            @change="checkStopDetailsFn()"></a-checkbox>
                                    </span>
                                    
                                    <!-- 类型 -->
                                    <div class="box folders-box" v-if="item.main_type == 7"
                                        @click.stop="checkDetailsFn(item)">
                                        <!-- 文件夹预览 -->
                                        <div class="preview-folder-box" v-if="item?.folder_pre_viewers">
                                            <img class="folderIcon" src="@/assets/img/folder.png" />
                                            <dl>
                                                <dd v-for="j in 4" :key="j">
                                                    <img :src="encodeURI1(item.folder_pre_viewers[j - 1]?.thumbnail)"
                                                        class="preview-cover-img"
                                                        v-if="item.folder_pre_viewers[j - 1]?.thumbnail" />
                                                </dd>
                                            </dl>
                                        </div>
                                        <!-- 默认 -->
                                        <img class="folderIcon" src="@/assets/img/folder.png" v-else />
                                        <div class="folderNum" v-if="item?.count">{{ item.count }}个媒资</div>
                                    </div>

                                    <!-- 标题 -->
                                    <p v-if="item.main_type == 7" class="title" :title="item.title" :x="item.title">
                                        <b :class="{foldertitle: item.main_type == 7}">{{ item.title }}</b>
                                        <star-filled v-if="item.favorite == 2" style="color: #f9601d;" />
                                        <span v-if="item.main_type != 7">{{ timestampToTimeFn(item.created_at) }}</span>
                                    </p>
                                </li>
                            </ul>
                        </a-checkbox-group>


                        <div class="label-tips-block">
                            <a-checkbox v-model:checked="state.checkAll">内容（10）</a-checkbox>
                        </div>
                        <a-checkbox-group v-model:value="state.checkedList">
                            <ul>
                                <li v-for="(item, index) in initDataArr"
                                :class="[ state.selectList.join(',').match(item.media_resource_id) ? 'active': '', item.main_type == 7 ? 'hiddenBox': '' ]"
                                    @mouseover.stop="handShowCheck(item)" :key="index">
                                    <!-- 复选框 -->
                                    <span v-if="item.main_type != 11" @click.stop class="checkbox-section"
                                        v-show="state.selectList.join(',').match(item.media_resource_id) || checkBoxItem == item.media_resource_id">
                                        <a-checkbox :value="item" :key="item.media_resource_id"
                                            @change="checkStopDetailsFn()"></a-checkbox>
                                    </span>
                                    <!-- 操作按钮 -->
                                    <img src="@/assets/img/more-icon.jpg" class="handleBtn"
                                        @click.stop="handStopClickListFn" />

                                    
                                    <!-- 类型 -->
                                    <div class="box" v-if="item.main_type == 1" @click.stop="checkDetailsFn(item)">
                                        <img class="cover-img" :src="encodeURI1(item.thumbnail)" />
                                        <!-- 标签 -->
                                        <p class="tags" v-if="item['tags']">
                                            <span v-for="(i, index) in item['tags']" :key="i">
                                                <b v-if="index < 3">{{ i }}</b>
                                            </span>
                                            <img src="@/assets/img/more-icon.jpg" class="tagsMore"
                                                v-if="item['tags'].length > 3" />
                                        </p>
                                    </div>
                                    <div class="box folders-box" v-else-if="item.main_type == 7" style="display: none;"
                                        @click.stop="checkDetailsFn(item)">
                                        <!-- 文件夹预览 -->
                                        <div class="preview-folder-box" v-if="item?.folder_pre_viewers">
                                            <img class="folderIcon" src="@/assets/img/folder.png" />
                                            <dl>
                                                <dd v-for="j in 4" :key="j">
                                                    <img :src="encodeURI1(item.folder_pre_viewers[j - 1]?.thumbnail)"
                                                        class="preview-cover-img"
                                                        v-if="item.folder_pre_viewers[j - 1]?.thumbnail" />
                                                </dd>
                                            </dl>
                                        </div>
                                        <!-- 默认 -->
                                        <img class="folderIcon" src="@/assets/img/folder.png" v-else />
                                        <div class="folderNum" v-if="item?.count">{{ item.count }}个媒资</div>

                                    </div>

                                    <div class="box" v-else-if="item.main_type == 3" @click.stop="checkDetailsFn(item)">
                                        <img class="folder-icon" src="@/assets/img/meadiaIndex/audio-cover.png" />
                                    </div>

                                    <div class="box video-box" v-else-if="item.main_type == 2"
                                        @click.stop="checkDetailsFn(item)">
                                        <img class="cover-img" :src="encodeURI1(item.thumbnail)" />
                                        <img src="@/assets/img/meadiaIndex/play-cover.png" class="playIcon" />
                                        <p class="tags" v-if="item['tags']">
                                            <span v-for="(i, index) in item['tags']" :key="i">
                                                <b v-if="index < 3">{{ i }}</b>
                                            </span>
                                            <img src="@/assets/img/more-icon.jpg" class="tagsMore"
                                                v-if="item['tags'].length > 3" />
                                        </p>
                                    </div>

                                    <div class="box" v-else-if="item.main_type == 6" @click.stop="checkDetailsFn(item)">
                                        <img src="@/assets/img/meadiaIndex/qita-cover.png" class="folder-icon" />
                                    </div>

                                    <div class="box" v-else-if="item.main_type == 11"
                                        @click.stop="checkDetailsFn(item)">
                                        <img class="folder-icon" style="width: 42%;"
                                            src="@/assets/img/meadiaIndex/solve-bg.png" />
                                    </div>

                                    <div class="box" v-else-if="item.main_type == 4" @click.stop="checkDetailsFn(item)">
                                        <img class="folder-icon" :src="encodeURI1(item.thumbnail)" />
                                        <img src="@/assets/img/meadiaIndex/txt-cover.png" class="folder-icon"
                                            v-if="item.url && item.url.match('.txt')" />
                                        <img src="@/assets/img/meadiaIndex/word-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.doc')" />
                                        <img src="@/assets/img/meadiaIndex/word-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.dot')" />
                                        <img src="@/assets/img/meadiaIndex/excle-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.xls')" />
                                        <img src="@/assets/img/meadiaIndex/epub-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.epub')" />
                                        <img src="@/assets/img/meadiaIndex/excle-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.et')" />
                                        <img src="@/assets/img/meadiaIndex/excle-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.xltx')" />
                                        <img src="@/assets/img/meadiaIndex/ppt-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.ppt')" />
                                        <img src="@/assets/img/meadiaIndex/ppt-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.pps')" />
                                        <img src="@/assets/img/meadiaIndex/ppt-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.pot')" />
                                        <img src="@/assets/img/meadiaIndex/pdf-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.pdf')" />
                                        <img src="@/assets/img/meadiaIndex/ppt-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.dps')" />
                                        <img src="@/assets/img/meadiaIndex/excle-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.xlt')" />
                                        <img src="@/assets/img/meadiaIndex/word-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.wps')" />
                                        <img src="@/assets/img/meadiaIndex/word-cover.png" class="folder-icon"
                                            v-else-if="item.url && item.url.match('.rtf')" />
                                        <img v-else src="@/assets/img/meadiaIndex/qita-cover.png" class="folder-icon" />
                                    </div>

                                    <!-- 标题 -->
                                    <p v-if="item.main_type != 7" class="title" :title="item.title" :x="item.title">
                                        <b :class="{foldertitle: item.main_type == 7}">{{ item.title }}</b>
                                        <star-filled v-if="item.favorite == 2" style="color: #f9601d;" />
                                        <span v-if="item.main_type != 7">{{ timestampToTimeFn(item.created_at) }}</span>
                                    </p>

                                    <!-- 操作选项 -->
                                    <div v-if="item.main_type == 11"></div>
                                    <div v-else class="handleBox">
                                        <div v-if="props.currentType == 'Recycle'">
                                            <p @click.stop="handDeleteFnConfirm(1, item)">彻底删除</p>
                                            <p @click.stop="handrestoreFn(1, item)">还原</p>
                                        </div>

                                        <div v-else>
                                            <p v-if="item.main_type == 7" @click.stop="checkDetailsFn(item, true)">打开</p>
                                            <p @click.stop="handNameFn(item)"
                                                v-if="props.currentType != 'Recycle' && currentRouteObj.btn6">重命名</p>
                                            <p @click.stop="downLoadFn(1, item)">下载</p>
                                            <p @click.stop="handMoveFn(1, item)"
                                                v-if="props.currentType != 'Recycle' && currentRouteObj.btn4">移动</p>
                                            <p @click.stop="handLikeFn(item)" v-if="item.favorite == 1 && item.main_type != 9 && item.main_type != 7">
                                                {{ item.favorite == 1 ? '收藏' : '取消收藏' }}</p>
                                            <p @click.stop="handLikeCancel(item)" v-else-if="item.favorite == 2 && item.main_type != 9 && item.main_type != 7">
                                                {{ item.favorite == 2 ? '取消收藏' : '收藏' }}</p>
                                            <p v-if="item.main_type == 7" @click.stop="handleEditFn(1, item)">编辑栏目</p>
                                            <p @click.stop="handSimilar(item)" v-if="item.main_type != 7 && item.main_type != 9">找相似</p>
                                            <p @click.stop="handDeleteFnConfirm(1, item)"
                                                v-if="props.currentType != 'Recycle' && currentRouteObj.btn5"> 删除</p>
                                        </div>
                                    </div>
                                    <!-- 审核状态 -->
                                    <div v-if="item.main_type != 7 && item.main_type != 11 && props.currentType != 'Recycle' && item.status"
                                        class="state-wrapper">
                                        <span v-if="item.status == 1" class="state-1">审核中</span>
                                        <span v-else-if="item.status == 2" class="state-2">已过审</span>
                                        <span v-else-if="item.status == 3" class="state-3">被拒绝</span>
                                    </div>
                                </li>
                            </ul>
                        </a-checkbox-group>
                    </div>
                    <!-- 无数据 -->
                    <div class="no-data-box" v-if="initDataArr && !initDataArr.length && carryFlag">
                        <img src="@/assets/img/meadiaIndex/noData-icon.png" class="no-data-icon" />
                        <span class="no-more-data"> 暂无数据 </span>
                    </div>

                    <!-- 无数据 -->
                    <div class="no-data-box" v-if="initDataArr && initDataArr.length && noMoreData"
                        style="position: initial;transform:initial;margin: 10px auto;">
                        <img src="@/assets/img/meadiaIndex/noData-icon.png" class="no-data-icon" />
                        <span class="no-more-data"> 已经到底了 </span>
                    </div>
                    <!-- loading -->
                    <div class="loading" v-show="loadFlag">
                        <a-spin />
                    </div>
                </div>

                <!-- 选择操作 -->
                <div class="select-operation-wrapper">
                    <div class="selected-num-wrapper">
                        <a-checkbox>全选</a-checkbox>
                        <p>已选<span>3</span>个媒资</p>
                    </div>
                    <div class="operation-btn-wrapper">
                        <a-button>移动至文件夹</a-button>
                        <a-button>下载</a-button>
                        <a-button>重命名3个文件</a-button>
                        <a-button>移入回收站</a-button>
                    </div>
                    <div class="selected-close">
                        <img src="@/assets/img/meadiaIndex/icon-close.png" alt="">
                    </div>
                </div>

                <!-- 移动弹框 -->
                <a-modal v-model:open="openFlag" :footer="null" width="680px" centered title="移动到" @cancel="cancelFn">
                    <a-radio-group v-model:value="currentMove" button-style="solid" style="margin-bottom: 10px;">
                        <a-radio-button
                            v-for="item in moveMenu" 
                            :key="item.id" 
                            :value="item.id">{{ item.name }}</a-radio-button>
                    </a-radio-group>
                    <div v-if="currentMove == 1" class="move-wrapper">
                        <div class="move-box">
                            <div class="title-hint">
                                <div class="bread-crumb" v-if="breadMoveCrumb?.length > 0">
                                    <div v-for="(v, i) in breadMoveCrumb" @click="changeMoveCrumb(v, i)" :key="i"
                                        class="bread-crumb-item">
                                        <span class="bread-crumb-line" v-if="i != 0">
                                            /
                                        </span>
                                        <span class="bread-crumb-word">
                                            {{ v.title }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <ul class="move" v-if="initFileArr.length != 0">
                                <li v-for="item in initFileArr" @click="changeFilesFn(item)" :test="item.id"
                                    :key="item">
                                    <div>
                                        <img class="cover-img" src="@/assets/img/meadiaIndex/folder-icon.jpg" />
                                        <p>{{ item.name }} </p>
                                    </div>
                                </li>
                            </ul>
                            <div class="no-data-box" v-else>
                                <img src="@/assets/img/meadiaIndex/noData-icon.png" class="no-data-icon" />
                                <span class="no-more-data"> 没有更多数据 </span>
                            </div>
                        </div>
                        <div class="btns-move">
                            <!-- <NewFileMove @createFolder="parentChangNewFolder"
                                v-if="props.currentType != 'Recycle' && currentRouteObj.btn1" /> -->
                            <div class="btns">
                                <button @click="cancelFn">取消</button>
                                <button class="active" @click="sureMoveFn">移动</button>
                            </div>
                        </div>
                        <div class="file-search">
                            <a-input-search v-model:value="searchFolder" placeholder="搜索" @change="changeInputSearch"  enter-button
                                @search="onSearchFolder" allow-clear/>
                        </div>
                    </div>
                    <div v-else class="move-wrapper">
                        <div class="move-box">
                            <div class="title-hint">
                                <div class="bread-crumb" v-if="breadMoveCrumb?.length > 0">
                                    <div v-for="(v, i) in breadMoveCrumb" @click="changeMoveCrumb(v, i)" :key="i"
                                        class="bread-crumb-item">
                                        <span class="bread-crumb-line" v-if="i != 0">
                                            /
                                        </span>
                                        <span class="bread-crumb-word">
                                            {{ v.title }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <ul class="move" v-if="initZutuArr.length != 0">
                                <li v-for="item in initZutuArr" @click="changeFilesFn(item)" :test="item.id"
                                    :key="item">
                                    <div>
                                        <img class="cover-img" src="@/assets/img/meadiaIndex/folder-icon.jpg" />
                                        <p>{{ item.name }} </p>
                                    </div>
                                </li>
                            </ul>
                            <div class="no-data-box" v-else>
                                <img src="@/assets/img/meadiaIndex/noData-icon.png" class="no-data-icon" />
                                <span class="no-more-data"> 没有更多数据 </span>
                            </div>
                        </div>
                        <div class="btns-move">
                            <div></div>
                            <div class="btns">
                                <button @click="cancelFn">取消</button>
                                <button class="active" @click="sureMoveFn">移动</button>
                            </div>
                        </div>
                    </div>
                </a-modal>

                <!-- 媒资重命名 -->
                <a-modal v-model:open="dialogVisibleName" title="媒资重命名" @ok="submitNameModel">
                    <div class="wrapper-new">
                        <label>媒资名称：</label>
                        <a-input v-model:value="selectItemName" placeholder="请输入文件名称" style="padding: 6px;" />
                    </div>
                </a-modal>

                <!-- 批量编辑媒资信息弹框 -->
                <!-- <CheckDialog ref="checkDialogRef" @refresh="refreshMediaList" :hanleType="'send'" /> -->
                <!-- 编辑栏目弹框 -->
                <EditClomn ref="editClomnRef" @refresh="refreshMediaList"></EditClomn>
                <!-- 编辑关联专题 -->
                <RelateTopics ref="relateTopicsRef" @refresh="refreshMediaList"></RelateTopics>
                
            </div>
            
            <!-- 右侧边栏信息 -->
            <SideInfo />
        </div>
    </main>
    </AdminLayout>
</div>
</template>
<script lang="ts" setup>
// import NewFile from "@/components/newFile.vue";
// import NewFileMove from "@/components/newFileMove.vue";
import { ref, reactive, onMounted, watch, h ,nextTick} from "vue";
// import Search from "@/components/search.vue";
// import SearchKeyWord from "@/components/searchKeyWord.vue";
// import CheckDialog from "@/views/Check/components/CheckDialog.vue"
import md5 from "md5";
import SideTree from "./components/SideTree.vue";
import EditClomn from "@/views/MediaIndex/components/EditClomn/index.vue";
import RelateTopics from "@/views/MediaIndex/components/RelateTopics/index.vue";
import AdminLayout from "@/components/AdminLayout/AdminLayout.vue";
import SideInfo from "@/components/SideInfo/index.vue";
import {
    senType,
    timestampToTimeFn,
    toTimestampStartFn,
    toTimestampEndFn,
    filterObj,
    mainTypeOption,
    searchOption_buy,
    searchOption_company,
    BreadCrumb,
    searchOption_my,
    timeArr,
    searchOption_recycle,
    encodeURI1
} from "@/utils/global";
import { uploadGray, tempUrl, mediaColumn, getSimilar, TypeNumCount } from "@/utils/mediaApi";
import request from "@/service/axios";
import { showBtnsFn } from '@/utils/auth';
import { message, Modal } from "ant-design-vue";
import { StarFilled, DownOutlined } from '@ant-design/icons-vue';
import { useFileInfoStore } from "@/store/fileInfo";
import { useGlobalStore } from '@/store/global';
import {  getDateRange, downloadIframe } from "@/utils/index";
import { useDemoStore } from "@/store/toBack";
import { useRouter, useRoute } from "vue-router";
import { initColumnCase } from "@/utils/mediaDetailApi";
const uperArr = ref<any>([]);
// 是否展示此树状组件
const isShowTree = ref(true)
// 编辑栏目弹框
const editClomnRef = ref()
// 编辑关联专题
const relateTopicsRef = ref()
const sideTreeRef = ref()
const searchRef = ref()

const searchText = ref('');
const useFileInfo = useFileInfoStore();
const useGlobal = useGlobalStore();
const router = useRouter();
const route = useRoute();
const currentTypeId = ref<string>("");
const currentType = ref<number>(1);
const openFlag = ref<boolean>(false);
const initDataArr = ref<any>([]);
const selectItem = ref<string>();
const editFlag = ref<boolean>(false);
const filterFlag = ref<boolean>(false);
const filterFlag1 = ref<boolean>(true);
const tabPosition = ref<string>("all");
const checkBoxItem = ref<string>();
const handShowItem = ref<string>();
const uperId = ref<string | undefined>();
const timeId = ref<string>('全部');
const carryFlag = ref<boolean>(false);
const dateVal = ref<any>([]);
const backStore = useDemoStore();
let IdsArr: any = [];
const initColumnArr: any = ref([]);
const isCriteria = ref(false)
const similarityFlag = ref<boolean>(false);
const similarityName = ref<string>();
const similarityItem = ref<any>();
const state = reactive({
    indeterminate: false,
    checkAll: false,
    checkedList: [],
    selectList: [],
});
const currentTabIndex = ref<string>("0");
const medianCount = ref<any>({
    "total": 0,
    "img": 0,
    "video": 0,
    "audio": 0,
    "doc": 0,
    "other": 0,
    "folder": 0,
    "atlas": 0,
});
const countHash = {
    0: "total",
    1: "img",
    2: "video",
    3: "audio",
    4: "doc",
    6: "other",
    7: "folder",
    9: "atlas",
};
const noMoreData = ref(false);
const pageItem = ref(30);
const is_top = ref<boolean>(searchOption_company.ifFolderTop);
// 批量编辑送审弹框
const checkDialogRef = ref<any>(null);
const tabsTable = ref<any>([]);
const moveMenu = ref([
    {
        id: 1,
        name: '文件夹'
    },
    {
        id: 2,
        name: '组图'
    }
]);
const showChild = ref(false);
const currentMove = ref(1);
// 是否显示树
const setShowTree = () => {
    isShowTree.value = !isShowTree.value
}
// 媒资统计
const getMedianCount = (item?:any,i?:any,t?:any) => {
    TypeNumCount({type:1,key:t,val:i}).then(res => {
        medianCount.value = res.data.result.data;
    });
}

// 回收站统计
const getMedianRecycleCount = () => {
    TypeNumCount({type:2}).then(res => {
        medianCount.value = res.data.result.data;
    });
}

// 文件上传置灰
const grayUploadList = (directory_id: string) => {
    uploadGray({
        location: '2',
        parent_id: directory_id
    }).then(res => {
        let arr = [];
        for (let i in res.data.result.data) {
            let is_repeat = false;
            for (let j in initDataArr.value) {
                if (res.data.result.data[i].id == initDataArr.value[j].file_id) {
                    is_repeat = true;
                    break;
                }
            }
            if (is_repeat) continue;
            arr.push({
                cover: res.data.result.data[i].thumbnail,
                created_at: res.data.result.data[i].creat_at,
                favorite: 1,
                file_id: res.data.result.data[i].id,
                if_source_valid: null,
                main_type: 11,
                media_resource_id: res.data.result.data[i].media_resource_id,
                resolution: null,
                source_id: null,
                status: null,
                tags: null,
                thumbnail: res.data.result.data[i].thumbnail,
                title: res.data.result.data[i].name,
                url: null,
                user_name: res.data.result.data[i].shared_user_id
            });
        }
        initDataArr.value = [...arr, ...initDataArr.value];
    });
}

const handleEnter = () => {
    useGlobal.setMediaBtn(true);
}

const handleLeave = () => {
    useGlobal.setMediaBtn(false);
}

// 新建hover
const handFileHover = () => {
    filterFlag.value = false;
};
// 栏目判断
const props = defineProps({
    currentType: {
        type: String,
    },
});
// 目录层级
const breadCrumb = ref<BreadCrumb[]>([
    {
        title: "全部",
        file_id: null,
    },
]);
// 刷新列表
const refreshMediaList = () => {
    cancelEditFn()
    SuccessfuCallbackFn()
}

// 刷新列表
const refreshListFn = (type?: any) => {
    tabsTable.value[Number(currentTabIndex.value)].searchObj["lastId"] = "";
    state.checkedList = [];
    (document.getElementById("admin-page") as any).scrollTop = 0;
    if (!type) {
        breadCrumb.value = [{ title: '全部', file_id: null }];
    }
};
// 新建监听   isTreeAdd表示是否左侧树里面的新增
const parentChang = (res: string,newFileObj?:any) => {
    tabPosition.value = 'all';
    if (res == 'folder-success' && useFileInfo.directory_id == '0') {
        tabsTable.value[Number(currentTabIndex.value)].searchObj["lastId"] = "";
        initDataArr.value = [];
        initDataFn(1);
    } else {
        tabsTable.value[Number(currentTabIndex.value)].searchObj["lastId"] = "";
        initDataArr.value = [];
        initDataFn(currentTypeId.value);
    }
    filterFlag.value = false;
       // 新增完，更新左侧对应树
    if(newFileObj){
        refreshTreAdd(newFileObj)
    }
 
};

// 移动新建文件夹
const parentChangNewFolder = (res: string) => {
    initMoveFn(useGlobal.directory_id_move);
};

// 操作成功回调
const SuccessfuCallbackFn = () => {
    tabsTable.value[Number(currentTabIndex.value)].searchObj["lastId"] = '';
    state.checkedList = [];
    similarityFlag.value = false;
    (document.getElementById("admin-page") as any).scrollTop = 0;
    breadMoveCrumb.value = [{ title: "全部", file_id: null }];
    if (currentTypeId.value == "") {
        initDataFn(1);
    } else {
        // 有子目录状态1
        initDataFn(currentTypeId.value);
    }
};

// 重置状态
const resetStatusFn = (isHanldeFilterObj:boolean) => {
    tabPosition.value = "all";
    tabsTable.value[Number(currentTabIndex.value)].searchObj["mainType"] = 0;
    uperId.value = undefined;
    tabsTable.value[Number(currentTabIndex.value)].searchObj["uperId"] = "";
    if(isHanldeFilterObj){
        for (let item in filterObj) {
            if (item == "ifDesc") {
                filterObj[item]["activeId"] = "true";
            } else if (item == "columns" || item == "source" || item == "goodsStatus") {
                filterObj[item]["activeId"] = '';
            }else if(['ifCompanyAndOrgGroup','status',].includes(item)){
                filterObj[item]["activeId"] = "0";
            }else {
                filterObj[item]["activeId"] = '';
            }
            tabsTable.value[Number(currentTabIndex.value)].searchObj[item] = filterObj[item]["activeId"];
        }
        backStore.filterObj = JSON.parse(JSON.stringify(filterObj))
        tabsTable.value[Number(currentTabIndex.value)].searchObj.start = '';
        tabsTable.value[Number(currentTabIndex.value)].searchObj.end = '';
    }else{
        if (dateVal.value.length>1) {
            tabsTable.value[Number(currentTabIndex.value)].searchObj["start"] = toTimestampStartFn(dateVal.value[0]);
            tabsTable.value[Number(currentTabIndex.value)].searchObj["end"] = toTimestampEndFn(dateVal.value[1]);
        } else {
            tabsTable.value[Number(currentTabIndex.value)].searchObj["start"] = '';
            tabsTable.value[Number(currentTabIndex.value)].searchObj["end"] = '';
        }
    }
    tabsTable.value[Number(currentTabIndex.value)].searchObj["lastId"] = "";
   
};
const resetFilterObj = () =>{
    for (let item in filterObj) {
        if (item == "ifDesc") {
            filterObj[item]["activeId"] = "true";
        } else if (item == "columns" || item == 'source' || item == "goodsStatus" ) {
            filterObj[item]["activeId"] = '';
        } else if(['ifCompanyAndOrgGroup','status',].includes(item)){
            filterObj[item]["activeId"] = "0";
        }else{
            filterObj[item]["activeId"] = '';
        }
        tabsTable.value[Number(currentTabIndex.value)].searchObj[item] = filterObj[item]["activeId"];
        backStore.filterObj = JSON.parse(JSON.stringify(filterObj))
    }
}
// 帅选状态清除
const clearfilterFn = () => {
    resetFilterObj()
    timeId.value = '全部'
    backStore.timeId = timeId.value
    dateVal.value = [];
    backStore.dateVal = dateVal.value 
    tabsTable.value[Number(currentTabIndex.value)].searchObj.start = '';
    tabsTable.value[Number(currentTabIndex.value)].searchObj.end = '';
    tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = '';
    initDataArr.value = []
    refreshListFn(1);

    if (similarityFlag.value) {
        handSimilar(similarityItem.value);
    } else {
        if (backStore.searchObj.text != '') {
            // 当有关键字搜索时候
            tabsTable.value[Number(currentTabIndex.value)].searchObj.searchFlag = ""
            nextTick(()=>{
                backSearchFn();
                rollToLoadFn();
            })
        }else if (currentTypeId.value == "") {
            initDataFn(1);
        } else {
            // 有子目录状态1
            initDataFn(currentTypeId.value);
        }
    }
    // 判断还有没有筛选条件
    setIsCriteria()
};
// 选择全部数据
const searchAllData = ()=>{
    changeCrumb({title:'全部'},0)
    // tabPosition.value ="all"
    // tabChangeTypeFn({target:{id:'0'}})
}
// 搜索tab切换 数据需更新标识
const searchTabStatus = ref(false);
// 类型选择
const tabChangeTypeFn = (value: any) => {
    const tempObj = mainTypeOption.find(item => item.type == value);
    filterFlag.value = false;
    state.checkAll = false;
    state.indeterminate = false;
    editFlag.value = false;
    state.checkedList = [];
    (document.getElementById("admin-page") as any).scrollTop = 0;
    tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = '';
    tabsTable.value[Number(currentTabIndex.value)].searchObj["mainType"] = tempObj?.val;
    backStore.netdiskObj.tabVal = tempObj?.type || '';

    // 相似tab 处理
    if (similarityFlag.value) {
        handSimilar(similarityItem.value);
        return;
    }
    if (!searchText.value) {
        tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = 0;
        if (currentTypeId.value == "") {
            refreshListFn();
            initDataFn(1);
            breadCrumb.value = [{ title: '全部', file_id: null }];
        } else {
            // 有子目录状态
            initDataFn(currentTypeId.value);
        }
    } else {
        searchTabStatus.value = true;
        tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 98 ? 97 : 98;
    }

};


// 上传人;
const changeUserFn = (value: string) => {
    tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 101 ? 101 : 102;
    tabsTable.value[Number(currentTabIndex.value)].searchObj["uperId"] = value;
    refreshListFn(1);
    if (currentTypeId.value == "") {
        initDataFn(1);
    } else {
        initDataFn(currentTypeId.value);
    }
    filterFlag.value = false;
};
const clearDate = () => {
    dateVal.value = []
    backStore.dateVal = dateVal.value 
    dateFnPre()
}
// 时间选择
const dateFnPre = (item?: any) => {
    timeId.value = '全部'
    backStore.timeId = timeId.value
    backStore.dateVal = dateVal.value
    setIsCriteria()
    // tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 100 ? 99 : 100;
    dateFn(item)
}
const dateFn = (item?: any) => {
    if (!item) {
        tabsTable.value[Number(currentTabIndex.value)].searchObj["start"] = '';
        tabsTable.value[Number(currentTabIndex.value)].searchObj["end"] = '';
    } else {
        tabsTable.value[Number(currentTabIndex.value)].searchObj["start"] = toTimestampStartFn(dateVal.value[0]);
        tabsTable.value[Number(currentTabIndex.value)].searchObj["end"] = toTimestampEndFn(dateVal.value[1]);
    }
    tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 101 ? 101 : 102;
    refreshListFn(1);

    if (similarityFlag.value) {
        handSimilar(similarityItem.value);
    } else {
        if (backStore.searchObj.text != '') {
            // 当有关键字搜索时候
            tabsTable.value[Number(currentTabIndex.value)].searchObj.searchFlag = ""
            nextTick(()=>{
                backSearchFn();
                rollToLoadFn();
            })
        } else if (currentTypeId.value == "") {
            initDataFn(1);
        } else {
            initDataFn(currentTypeId.value);
        }
    }

    // 判断还有没有筛选条件
    setIsCriteria()
};
const changeTimeFn = (item: any) => {
    // tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 100 ? 99 : 100;
    timeId.value = item;
    backStore.timeId =  timeId.value
    if (item == '近一周') {
        dateVal.value = getDateRange(7);
        dateFn(dateVal.value)
    } else if (item == '近一月') {
        dateVal.value = getDateRange(30);
        dateFn(dateVal.value)
    } else if (item == '近三月') {
        dateVal.value = getDateRange(3 * 30);
        dateFn(dateVal.value)
    } else if (item == '近六月') {
        dateVal.value = getDateRange(6 * 30);
        dateFn(dateVal.value)
    } else if (item == '近一年') {
        dateVal.value = getDateRange(12 * 30);
        dateFn(dateVal.value)
    } else if (item == '近三年') {
        dateVal.value = getDateRange(3 * 12 * 30);
        dateFn(dateVal.value)
    } else {
        dateVal.value = [];
        dateFn();
    }
    backStore.dateVal = dateVal.value 
}
// 判断是否展示筛选条件
const setIsCriteria = () => {
    if (dateVal.value && dateVal.value.length > 0) {
        isCriteria.value = true
        return
    }
    for (let item in filterObj) {
        // 排序如果是时间倒序不显示筛选
        if (item == "ifDesc") {
            if (filterObj[item]["activeId"] == 'false') {
                isCriteria.value = true
                return
            }

        } else if (item == "columns" || item == 'source') {
            // 栏目有筛选
            if (filterObj[item]["activeId"] && filterObj[item]["activeId"]?.length > 0) {
                isCriteria.value = true
                return
            }
        } else if(item == "goodsStatus"){
           if(filterObj[item]["activeId"]!==""){
                isCriteria.value = true
                return
           }
        }else if (filterObj[item]["activeId"] != 0) {
            isCriteria.value = true
            return
        }
    }

    isCriteria.value = false
}
// 条件显示筛选条件
const controlShowFilter = (v:any,i:string)=>{
    if(i==="ifDesc"){ // 时间倒序判断
        if(v.activeId=='false'){
            return true
        }
        return false    
    }
    if(i==='goodsStatus'){ // 交易状态判断
        if(v.activeId===''){
            return false
        }
        return true 
    }
    if( ['ifCompanyAndOrgGroup','status'].includes(i)){ // 审核状态判断
        if(v.activeId==='0' || v.activeId===''){
            return false
        }
        return true 
    }
    
    if(v.activeId){ //其他的判断
        return true
    }else{
        return false
    }
    
}
// x掉某个筛选
const clearFilterTextFn = (v: any, type: string) => {
    if (type == "ifDesc") {
        v["activeId"] = "true";
    } else if (type == "columns" || type == 'source' || type == "goodsStatus" ) {
        v["activeId"] = '';
    } else if(['ifCompanyAndOrgGroup','status',].includes(type)){
        v["activeId"] = "0";
    }else{
        v["activeId"] = '';
    }
    filterTextFn(v, { id: v.activeId }, type)
}
// x掉某个栏目
const clearCloneFilterTextFn = (v: any, item: any, index: any) => {
    filterTextFn(v, { id: item }, 'columns')
}
//  关键字体筛选，带上某一个过滤的条件
const setSingeSearchFilter = (item: any, i: any, type: string) => {
    if (type == "columns") {
        if (i.id) {
            if(item.activeId && typeof(item.activeId) =="string"){
                item.activeId = item.activeId.split(",")
            }
            if (Array.isArray(item.activeId) && item.activeId.length > 0) {
                const _i = item.activeId.findIndex(v => {
                    return v == i.id
                })
                if (_i != -1) {
                    item.activeId.splice(_i, 1)
                } else {
                    item.activeId.push(i.id)
                }
            } else {
                item.activeId = [i.id]
            }
        } else {
            item.activeId = []
        }
        tabsTable.value[Number(currentTabIndex.value)].searchObj[type] = item.activeId.join(",");
        // 防止类型改变
        filterObj[type].activeId = item.activeId.join(",");
    } else {
        item.activeId = i.id;
        tabsTable.value[Number(currentTabIndex.value)].searchObj[type] = i.id;
    }
}

const selectDesc = (value: string) => {
    filterTextFn(filterObj['ifDesc'], filterObj['ifDesc']['val'].find(item => item.id == value), 'ifDesc');
}

// 其它筛选
const filterTextFn = (item: any, i: any, type: string) => {
    (document.getElementById("admin-page") as any).scrollTop = 0;
    tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = "";
    initDataArr.value = [];
    getMedianCount(item,i,type);
    // 栏目改成多选
    setSingeSearchFilter(item,i,type)

    // tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 101 ? 101 : 102;
    refreshListFn(1);
    if (similarityFlag.value) {
        handSimilar(similarityItem.value);
    } else {
        if (backStore.searchObj.text != '') {
            // 当有关键字搜索时候
            tabsTable.value[Number(currentTabIndex.value)].searchObj.searchFlag = ""
            nextTick(()=>{
                backSearchFn();
                rollToLoadFn();
            })
        }else if (currentTypeId.value == "") {
            initDataFn(1);
        } else {
            initDataFn(currentTypeId.value);
        }
    }
    backStore.filterObj = JSON.parse(JSON.stringify(filterObj))
    // 判断还有没有筛选条件
    setIsCriteria()
};


// 栏目初始化
mediaColumn().then((res) => {
    res.unshift({ name: "全栏目", id: "" });
    filterObj["columns"].val = res;
});



const filterTagsFn = () => {
    filterFlag.value = filterFlag.value ? false : true;
    filterFlag1.value = filterFlag1.value ? false : true;
    editFlag.value = false;
};

const changeCrumb = (item: BreadCrumb, i: number) => {
    similarityFlag.value = false;
    breadCrumb.value.splice(i + 1);
    const directory_id = item.media_resource_id ? item.media_resource_id : '0';
    useFileInfo.setDirectoryId(directory_id.toString());
    currentTypeId.value = "";
    state.checkedList.length = 0;
    state.checkAll = false;
    backStore.netdiskObj.currentTypeId = "";
    (document.getElementById("admin-page") as any).scrollTop = 0;
    tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 101 ? 101 : 102;
    if (item.media_resource_id) {
        checkDetailsFn(item);
        setSelectedKeys([item.media_resource_id])
    } else {
        if (props.currentType == 'Recycle') {
            getMedianRecycleCount();
        } else {
            getMedianCount();
        }
        // 清除状态
        currentTypeId.value = "";
        tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = '';
        tabsTable.value[Number(currentTabIndex.value)].searchObj.mainType = 0;
        initDataArr.value = [];
        initDataFn(1);
        useFileInfo.setDirectoryId('0');
        tabPosition.value = "all";
        setSelectedKeys([])

    }
};

// tab切换
const hdlChangeTab = (activeKey: string) => {
    filterFlag.value = false;
    refreshListFn(1);
    resetStatusFn(true);
    initDataFn(1);
};
const handStopClickListFn = () => {
};

// 取消选择
const cancelEditFn = () => {
    state.checkedList = [];
};
// 滚动加载更多
const pageFlag = ref<boolean>(false);
const loadFlag = ref<boolean>(false);
const initDataFn = async (item: any) => {
    
    pageFlag.value = false;
    loadFlag.value = true;
    tabsTable.value[Number(currentTabIndex.value)].searchObj.folder_id = useFileInfo.directory_id;
    if (item == 1) {
        await request({
            url: "/mediaresource-manage-service/medias",
            method: "get",
            params: tabsTable.value[Number(currentTabIndex.value)]
                .searchObj,
        }).then((res) => {
            loadFlag.value = false;
            if (tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId == "") {
                initDataArr.value = [];
                // 拉取处理中的数据
                grayUploadList(useFileInfo.directory_id);
            }
            tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = res.data.result.page.last_id;
            initDataArr.value = [...initDataArr.value, ...res.data.result.data];
            if (res.data.result.data.length == 0 || res.data.result.data.length < 30) {
                pageFlag.value = true;
            }
            // 执行一次
            setTimeout(() => { carryFlag.value = true; }, 100);
        });

    } else {
        // 子目录
        await request({
            url: "/mediaresource-manage-service/medias/folders/" + item.media_resource_id,
            method: "get",
            params: tabsTable.value[Number(currentTabIndex.value)].searchObj,
        }).then((res) => {
            loadFlag.value = false;
            if (tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId == "") {
                initDataArr.value = [];

                // 拉取处理中的数据
                grayUploadList(useFileInfo.directory_id);
            }
            initDataArr.value = [...initDataArr.value, ...res.data.result.data];
            tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = res.data.result.page.last_id;
            if (res.data.result.data.length == 0 || res.data.result.data.length < 30) {
                pageFlag.value = true;
            }
            // 执行一次
            setTimeout(() => { carryFlag.value = true; }, 100)
        });
    }
};

// 加载更多
const rollToLoadFn = () => {
    const rollContainer = document.querySelector('#admin-page') as HTMLElement;
    rollContainer.addEventListener("scroll", () => {
        const clientHeight = rollContainer.clientHeight;
        const scrollTop = rollContainer.scrollTop;
        const scrollHeight = rollContainer.scrollHeight;
        if (scrollTop > 0 && Number(clientHeight) + Number(Math.floor(scrollTop)) >= Number(scrollHeight) - 5 && !loadFlag.value) {
            // console.log("到底了")
            if (pageFlag.value) {
                return;
            }
            // loadFlag.value = true;
            // 搜索判断
            if (searchText.value) {
                if (!noMoreData.value) {
                    tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = initDataArr.value[initDataArr.value.length - 1].page.last_id;
                    tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 98 ? 97 : 98;
                }
                return;
            }

            //  找相似判断
            if (similarityFlag.value) {
                handSimilar(similarityItem.value);
                return;
            }

            //列表滚动
            if (currentTypeId.value == '') {
                initDataFn(1);
            } else {
                initDataFn(currentTypeId.value);
            }
        }
    });
};
// 初始化参数入口
const initFn = ()=>{
    initDataArr.value = []
    if (props.currentType == "My") {
        tabsTable.value = [{ searchObj: searchOption_my }];
        resetStatusFn(true);
    } else if (props.currentType == "Recycle") {
        filterFlag1.value = false;
        tabsTable.value = [{ searchObj: searchOption_recycle }];
        resetStatusFn(true);
    } else {
       const searchCompany = {searchObj:searchOption_company}
        for (let item in  backStore.filterObj) {
            filterObj[item] =  backStore.filterObj[item]
            searchCompany.searchObj[item] = filterObj[item]["activeId"];
        }
        tabsTable.value = [searchCompany, { searchObj: searchOption_buy }];
        dateVal.value = backStore.dateVal
        timeId.value = backStore.timeId
        resetStatusFn(false);
        setIsCriteria()
    }
}
initFn()
// 数据初始化
onMounted(async () => {
    /*
    // 上传人;
    tempUrl().then((res) => {
        const { userInfo } = window.microApp.getGlobalData();
        let arr: any = [];
        arr = [...uperArr.value, ...res];
        arr.map((item: any, index: number) => {
            if (item.userName == userInfo.userName) {
                arr.splice(index, 1);
                arr.unshift({ userId: userInfo.userId, userName: '我自己' });
            }
        });
        uperArr.value = arr;
        uperArr.value.unshift({ userId: '', userName: "全部" });
    });
    */
    // 判断是否找相似返回
    if (backStore.similarityObj.title != '') {
        backSimilarityFn();
        rollToLoadFn();
        return;
    };
    if (props.currentType == 'Recycle') {
        getMedianRecycleCount();
    } else {
        getMedianCount();
    }
    // 判断是否搜索返回
    if (backStore.searchObj.text != '') {
        backSearchFn();
        rollToLoadFn();
        return;
    };
    //是否目录层级返回
    if (backStore.netdiskObj.currentTypeId == '') {
        
        initDataFn(1);
        useFileInfo.setDirectoryId("0");
        // 加载更多
        rollToLoadFn();
    } else {
        // 返回重置状态
       
        breadCrumb.value = backStore.netdiskObj.breadCrumb;
        currentTypeId.value = backStore.netdiskObj.currentTypeId;
        tabsTable.value[Number(currentTabIndex.value)].lastId = '';
        tabsTable.value[Number(currentTabIndex.value)].searchObj = backStore.netdiskObj.status;

        tabsTable.value[Number(currentTabIndex.value)].searchObj.mainType = backStore.netdiskObj.status.mainType;
        tabPosition.value = backStore.netdiskObj.tabVal || "all";

        uperId.value = backStore.netdiskObj.status.uperId;
        // 加载更多
        initDataFn(backStore.netdiskObj.currentTypeId);
        rollToLoadFn();
    }
});

//  搜索返回alert
const backSearchFn = () => {
    searchText.value = backStore.searchObj.text;
    breadCrumb.value = backStore.netdiskObj.breadCrumb;
    tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = 9527;
};

//  找相似返回
const backSimilarityFn = () => {
    similarityFlag.value = true;
    breadCrumb.value = backStore.netdiskObj.breadCrumb;
    tabsTable.value[Number(currentTabIndex.value)].lastId = '';
    similarityName.value = backStore.similarityObj.title;
    handSimilar({ title: backStore.similarityObj.title, media_resource_id: backStore.similarityObj.id })
};

//  显示复选框
const handShowCheck = (item: any) => {
    checkBoxItem.value = item.media_resource_id;
    if (state.checkedList.length == 0) {
        handShowItem.value = item.media_resource_id;
    }
};
const checkStopDetailsFn = () => {
    selectItem.value = "";
    handShowItem.value = "";
};

// 全选
const onCheckAllChange = (e: any) => {
    Object.assign(state, {
        checkedList: e.target.checked ? initDataArr.value : [],
        indeterminate: false,
    });
};

// 媒资处理
watch(() => useFileInfo.processStatus, (val) => {
    // 上传成功刷新页面
    if (useFileInfo.processStatus.refresh_type == 'inProcess' && 
        (
            (useFileInfo.processStatus.refresh &&  useFileInfo.directory_id == useFileInfo.processStatus.websocketInfo.media.parent_id)
        )) {
        useFileInfo.setProcessStatus({
            refresh_type: '',
            websocketInfo: {},
            refresh: false,
        });

        initDataArr.value.unshift({
            ...useFileInfo.processStatus.websocketInfo.media,
            main_type: 11
        });
    }
    // 处理成功的媒资
    if (useFileInfo.processStatus.refresh && useFileInfo.processStatus.refresh_type == 'processSuccess') {
        useFileInfo.setProcessStatus({
            refresh_type: '',
            websocketInfo: {},
            refresh: false,
        });
        for (let i in initDataArr.value) {
            if (initDataArr.value[i].media_resource_id == useFileInfo.processStatus.websocketInfo.media.media_resource_id) {
                initDataArr.value[i] = useFileInfo.processStatus.websocketInfo.media;
                break;
            }
        }
    }
});

watch(
    () => state.checkedList,
    (val) => {
        if (initDataArr.value.length == 0) {
            return;
        }
        state.indeterminate =
            !!val.length && val.length < initDataArr.value.length;
        state.checkAll = val.length === initDataArr.value.length;
        IdsArr = [];
        state.checkedList.map((item: any, index: number) => {
            IdsArr.push(item.media_resource_id);
        });
        state.selectList = IdsArr;
    },
);
// 路由监听
const currentRouteObj: any = ref({})
watch(() => router.currentRoute.value.path, (newValue, oldValue) => {
    // // 权限
    currentRouteObj.value = showBtnsFn(newValue);
    // 防止切换路由，导致tab定位不对，只有取详情时候才保存定位
    if(oldValue && !["/admin/mediaDetails","/admin/zutuDetail"].includes(newValue)){
        backStore.netdiskObj.tabVal = "all"
        if(oldValue=="/admin/index"){
            backStore.dateVal = []
            backStore.timeId =  "全部"
            resetFilterObj()
        }
    }
    //  路由
    if (backStore.netdiskObj.backStatus == backStore.netdiskObj.goStatus) {
        backStore.netdiskObj.backStatus = 0;
        backStore.netdiskObj.goStatus = 10;
    } else if (["/admin/mediaDetails","/admin/zutuDetail" ].includes(newValue)) {
    } else {
        // 离开路由设置初始状态
        backStore.netdiskObj.currentTypeId = '';
        backStore.similarityObj.title = '';
        backStore.searchObj.text = '';
    }
}, { immediate: true });
// 重命名
const selectName = ref<string>();
const dialogVisibleName = ref<boolean>(false);
const selectItemObj = ref<any>({});
const selectItemName = ref<string>('');
const handNameFn = (item: any) => {
    filterFlag.value = false;
    selectName.value = item.media_resource_id;
    selectItem.value = "";
    selectItemName.value = item.title;
    selectItemObj.value = item;
    dialogVisibleName.value = true;
};

const submitNameModel = () => {
    if (selectItemName.value == "") {
        message.info("请输入名称");
        return;
    }
    submitNameFn(selectItemName.value, selectItemObj.value);
}

const submitNameFn = (name: string, item: any) => {
    let nameObj: senType;
    if (item.type == 7) {
        nameObj = {
            folder_id: item.media_resource_id,
            location: 2,
            new_name: name,
        };
    } else {
        nameObj = {
            file_id: item.media_resource_id,
            location: 2,
            new_name: name,
        };
    }
    request({
        url: `/mediaresource-manage-service/medias/${item.media_resource_id}`,
        method: "put",
        data: {
            title: name
        },
    }).then((res) => {
        if (res.data.status_code == 1) {
            message.success("重命名成功");
            dialogVisibleName.value = false;
        } else {
            message.error("重命名失败");
        }
        selectName.value = "";
        SuccessfuCallbackFn();
        // 递归更新左侧树名称
        refreshTreeName({id:item.media_resource_id,name})
        // 面包屑名称可能需要实时更新
        // breadCrumb
        const _o:any = breadCrumb.value.find(v => {
            return v.media_resource_id ==item.media_resource_id
        })
        if(_o){
            _o.title = name
        }
    });
};

// 查看子目录
const checkDetailsFn = (item: any, openWindows?: boolean) => {
    // 未处理成功的数据
    if (item.main_type == 11) {
        message.info("媒资处理中");
        return;
    }
    if (state.checkedList.length > 0) {
        return;
    }
    state.checkedList = [];
    if (!JSON.stringify(breadCrumb.value).match(item.media_resource_id) && item.main_type == 7) {
        breadCrumb.value.push(item);
    }

    // 记住详情状态
    backStore.netdiskObj.breadCrumb = breadCrumb.value;
    backStore.netdiskObj.status = tabsTable.value[Number(currentTabIndex.value)].searchObj;

    if (item.main_type == 7) {
        tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 101 ? 101 : 102;
        // 媒资数据统计
        // if (props.currentType == 'Recycle') {
        //     getMedianRecycleCount(item.media_resource_id);
        // } else {
        //     getMedianCount(item.media_resource_id)
        // }
        backStore.netdiskObj.currentTypeId = item;
        currentType.value = item;
        currentTypeId.value = item;
        tabPosition.value = "all";
        tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = "";
        tabsTable.value[Number(currentTabIndex.value)].searchObj.mainType = 0;
        (document.getElementById("admin-page") as any).scrollTop = 0;
        useFileInfo.setDirectoryId(item.media_resource_id);
        initDataFn(item);
        // 进入文件夹后，左侧树高亮显示
        setSelectedKeys([item.media_resource_id])
    } else if (item.main_type == 9) {
        router.push(`/admin/zutuDetail?id=${item.media_resource_id}&location=1&listType=${props.currentType == 'Recycle'? 3: 1}`);
        backStore.netdiskObj.goStatus = 1;
    } else {

        //跳转详情
        if (props.currentType == 'Recycle') {
            router.push(`/admin/mediaDetails?id=${item.media_resource_id}&location=2`);
            backStore.netdiskObj.goStatus = 2;
        } else {
            if (!openWindows) router.push(`/admin/mediaDetails?id=${item.media_resource_id}&location=1`);
            else window.open(`/mrc-admin/admin/mediaDetails?id=${item.media_resource_id}&location=1`);
            backStore.netdiskObj.goStatus = 1;
            if (similarityFlag.value) {
                backStore.similarityObj.title = similarityName.value;

            }
            if (searchText.value != '') {
                backStore.searchObj.text = searchText.value;

            }
        }

    }
};
// 批量编辑
const batchEdit = () => {
    if (state.checkedList.length == 0) {
        message.warning("请选择数据");
        return
    }
    const bol = state.checkedList.some(v => {
        return !v.file_id
    })
    if (bol) {
        message.warning("不能选择文件夹/组图");
        return
    }
    if (state.checkedList.length > 60) {
        message.warning("最多选择60条数据");
        return
    }
    checkDialogRef.value.setDailogVisible(state.selectList)
}
// 添加确认弹框
const handDeleteFnConfirm = (type: number, item: any) => {
    Modal.confirm({
        content: '确定删除媒资?',
        okText: '确认',
        cancelText: '取消',
        onOk() {
            handDeleteFn(type, item);
        }
    });
}

// list 操作- 删除
const handDeleteFn = (type: number, item: any) => {
    // if (!confirm("确定删除媒资?")) { return }
    let postObj: senType = {
        is_media: 1,
    };
    // 3表示回收站
    if (props.currentType == 'Recycle') {
        postObj.location = 2;
    } else {
        postObj.location = 1;
    }
    let IdArr: any = [];

    if (type == 1) {
        if (item.main_type == 7) {
            postObj.folder_id = item.media_resource_id;
            delete postObj.file_id;
            delete postObj.files;
        } else {
            postObj.file_id = item.media_resource_id;
            delete postObj.folder_id;
            delete postObj.files;
        }
    } else if (type == 2) {
        if (state.checkedList.length == 0) {
            message.error("选择文件");
            return;
        }
        item.map((i: any) => {
            IdArr.push(i.media_resource_id);
        });
        postObj.files = IdArr;
        delete postObj.file_id;
        delete postObj.folder_id;
    }
    request({
        url: "/mediaresource-manage-service/resource/file",
        method: "delete",
        data: postObj,
    }).then(() => {
        selectItem.value = "";
        message.success("删除成功");
        SuccessfuCallbackFn();
        if (props.currentType == 'Recycle') {
            getMedianRecycleCount();
        } else {
            getMedianCount();
        }
        if(type == 2){
            // 批量删除的左侧树重置
            resetTreeData()
        }else{
            refreshDeleteData({...item,id:item.media_resource_id})
        }
    });
};

// 收藏
const handLikeFn = (data: any) => {
    filterFlag.value = false;
    request({
        url: "/mediaresource-manage-service/usermedias/medias/" + data.media_resource_id,
        method: "post",
    }).then((res) => {
        data.favorite = 2
        if (res.data.status_code == 1) message.success("收藏成功");
        else message.error(res.data.msg);
    }).catch((err) => {
    });
};

// 取消收藏成功
const handLikeCancel = (data: any) => {
    request({
        url:
            "/mediaresource-manage-service/usermedias/medias/" +
            data.media_resource_id,
        method: "delete",
    }).then(() => {
        data.favorite = 1
        message.success("取消收藏成功");
    });
};

// 初始化栏目
initColumnCase().then((res: any) => {
    initColumnArr.value = res;
});
// 关联专题
const relateTopicsFn = ( data: any)=>{
    // 批量时候不能选择组图
    const bol = state.checkedList.some((v:any) => {
          return v.main_type!= 7
      })
      if (bol) {
          message.warning("只能选择文件夹");
          return
      }
      relateTopicsRef.value?.handleEditFn(data)
}
// 栏目编辑
const handleEditFn = (type: number, data: any) => {
  if(type==2){
    // 批量时候不能选择组图
      const bol = state.checkedList.some((v:any) => {
          return v.main_type== 9
      })
      if (bol) {
          message.warning("不能选择组图");
          return
      }
  }
  editClomnRef.value?.handleEditFn(type,data,{initColumnArr:initColumnArr.value})
};


// 下载
const downLoadFn = (type: number, data: any) => {
    loadFlag.value = true;
    let get_parent_id = breadCrumb.value.length > 1 ? breadCrumb.value.slice(-1)[0]['id'] : 0;
    filterFlag.value = false;
    let downObj: any = {};
    let IdArr: any = [];
    downObj.parent_id = get_parent_id;
    downObj.location = 2;
    downObj.equipment = 2;
    // 1 单个  // download_type 1 单个文件， 2 单个文件夹/批量文件 // 0 文佳夹
    if (type == 1) {
        downObj.files = [data.media_resource_id];
        downObj.download_type = data.main_type == 7 ? 2 : 1;
        if (data.main_type == 7) {
            downFileFn(downObj);
        } else {
            downFileFn(downObj, data.url);
        }
    } else if (type == 2) {

        if (state.checkedList.length == 0) {
            message.error('选择文件');
            return;
        }
        data.map((i: any) => {
            IdArr.push(i.media_resource_id)
        });
        downObj.files = IdArr;
        downObj.download_type = 2;

        downFileFn(downObj);
    }
};
const downFileFn = (data: any, url?: any) => {
    request({
        url: "/mediaresource-manage-service/resource/file",
        method: "POST",
        data: data,
    }).then((res) => {
        loadFlag.value = false;
        if (data.download_type == 2) {
            message.success('下载成功');
            // window.open(res.data.result.data)
            location.href = res.data.result.data
        } else {
            downloadIframe(res.data.result.data)
        }
        state.checkedList = [];
        editFlag.value = false;
    });
};

const initZutuArr = ref<any>([]);
const initZutuMoveFn = (someArr: any, folderId: string | number) => {
    request({
        url: "/mediaresource-manage-service/resource/hierarchy/atlas",
        method: "post",
        data: {
            files: someArr,
            folder_id: folderId,
            location: 2
        }
    }).then((res) => {
        initZutuArr.value = [];
        initZutuArr.value = res.data.result.data;
    });
};

//移动
const initFileArr = ref<any>([]);
let moveTypeObj: senType = {
    location: 2,
    target_id: 0,

};
const initMoveFn = (folderId: number | string = 0) => {
    let arr: any = [];
    if (moveTypeObj.file_id) {
        arr = [moveTypeObj.file_id]
    } else if (moveTypeObj.folder_id) {
        arr = [moveTypeObj.folder_id]
    } else {
        arr = moveTypeObj.files
    }
    filterFlag.value = false;
    if(currentMove.value == 2 && breadMoveCrumb.value.length > 1) {
        initZutuArr.value = [];
        return;
    } 
    // 组图
    initZutuMoveFn(arr, folderId);
    request({
        url: "/mediaresource-manage-service/resource/hierarchy/folder",
        method: "post",
        data: {
            files: arr,
            folder_id: folderId,
            location: 2
        }
    }).then((res) => {
        initFileArr.value = [];
        initFileArr.value = res.data.result.data;
    });
};
const breadMoveCrumb = ref<BreadCrumb[]>([
    {
        title: "全部",
        file_id: null,
    },
]);

const changeMoveCrumb = (item: any, i: number) => {
    breadMoveCrumb.value.splice(i + 1);
    if (item.id) {
        moveTypeObj.target_id = item.id;
        initMoveFn(item.id);
        useGlobal.setMoveDirectoryId(item.id);
    } else {
        moveTypeObj.target_id = 0;
        initMoveFn();
        useGlobal.setMoveDirectoryId(0);
    }
};
let moveName = "";
const handMoveFn = (type: number, item: any) => {
    moveName = item.title;
    moveTypeObj.target_id = 0;
    moveTypeObj.if_merge = false;
    let IdArr: any = [];
    if (type == 1) {
        openFlag.value = true;
        if (item.type == 7) {
            moveTypeObj.folder_id = item.media_resource_id;
            delete moveTypeObj.file_id;
        } else {
            moveTypeObj.file_id = item.media_resource_id;
            delete moveTypeObj.folder_id;
        }

    } else {
        if (state.checkedList.length == 0) {
            message.error("选择文件");
            return;
        }
        openFlag.value = true;
        item.map((i: any) => {
            IdArr.push(i.media_resource_id);
        });
        moveTypeObj.files = IdArr;
        delete moveTypeObj.file_id;
        delete moveTypeObj.folder_id;
    }

    initMoveFn();
};
//
const targetCheckedId = ref<string>("");
const changeFilesFn = (item: any) => {
    targetCheckedId.value = item.id;
    moveTypeObj.target_id = item.id;
    directoryPathName.value = item.name;
    if (!JSON.stringify(breadMoveCrumb.value).match(item.id)) {
        breadMoveCrumb.value.push({
            title: item.name,
            ...item
        });
    }
    // 进入的目录
    useGlobal.setMoveDirectoryId(item.id);
    initMoveFn(item.id);
};


const successMove = () => {
    const tprops = {
        style: { marginLeft: "10px" },
        href: 'javascript:;',
        onClick: async () => {
            backStore.netdiskObj.currentTypeId = {media_resource_id: directoryPathId.value}
            await backStore.setBreadCrumbById()
            breadCrumb.value = backStore.netdiskObj.breadCrumb;
            if( backStore.netdiskObj.currentTypeId.media_resource_id){
                checkDetailsFn({
                    media_resource_id: directoryPathId.value,
                    title: directoryPathName,
                    main_type: currentMove.value == 2 ? 9 : 7 
                });
            }else{
                initDataFn(1)
                // 树状结构设置未选中
                setSelectedKeys([])
            }
            modal.destroy();
        }
    };
    const modal = Modal.success({
        title: '移动成功',
        okText: '返回',
        content: h('div', {}, [
            h('span', '移动成功,'),
            h('a', tprops, '立即查看!')
        ]),
    });
};

//移动搜索文件夹
const searchFolder = ref<string>("");
// const changeInputSearch=()=>{
//     initMoveFn()
// };
const onSearchFolder = () => {
    let folder_id=breadMoveCrumb.value.length>1?breadMoveCrumb.value[breadMoveCrumb.value.length-1]['id']:0
    if(searchFolder.value==''){
        initMoveFn(folder_id)
        return
    }
    request({
        url: "/multimodal-search-service/mediaresource/search",
        method: "post",
        data: {
            aiAnalysisStatus: 0,
            end: "",
            folder_id:folder_id,
            ifChildMediaResource: 0,
            ifCompanyAndOrgGroup: 0,
            ifHadBuy: 0,
            ifTimeDesc: true,
            lastId: 0,
            listType: 1,
            mainType: "7",
            query_text: searchFolder.value,
            query_type: 0,
            searchFlag: 0,
            start: "",
            status: 0,
            uperId: ""
        }
    }).then(res => {
        initFileArr.value = [];
        for (let i in res.data.result.data) {
            initFileArr.value.push({
                id: res.data.result.data[i].media_resource_id,
                name: res.data.result.data[i].title,
                parent_id: "0"
            });
        }
    });
}

const directoryPathId = ref(0) as any;
const directoryPathName = ref("全部");
const sureMoveFn = () => {
    const value = initFileArr.value.find(e => e.name == moveName);
    if (value) {
        if (!confirm('确定合并相同新文件夹')) { return; }
        moveTypeObj.if_merge = true;

    }
    moveTypeObj.target_id = moveTypeObj.target_id == 0 ? 0 : moveTypeObj.target_id;
    directoryPathId.value = moveTypeObj.target_id;
    request({
        url: "/mediaresource-manage-service/resource/path",
        method: "put",
        data: moveTypeObj,
    }).then(() => {
        SuccessfuCallbackFn();
        successMove();
        // 移动成功后，更新左侧数据
        if(moveTypeObj.file_id){
            // 单个移动
            refreshTreeMoveData(moveTypeObj)
        }else{
            //  批量移动全量更新左侧树
            resetTreeData()
        }
        moveName = "";
        openFlag.value = false;
        moveTypeObj.target_id = 0;
        initFileArr.value = [];
        moveTypeObj.if_merge = false;

    });
};

// 找相似
let similarLastId = '';
const handSimilar = (item?: any) => {
    loadFlag.value = true;
    filterFlag1.value = false;
    if (item.media_resource_id == similarityItem.value?.media_resource_id) {
    } else {
        similarityItem.value = item;
        (document.getElementById("admin-page") as any).scrollTop = 0;
        similarLastId = '';
    }
    similarityName.value = item.title;
    filterFlag.value = false;
    let obj = { columns: [] };
    obj.columns = tabsTable.value[Number(currentTabIndex.value)].searchObj.columns.split(",");
    let mergedObj = { ...tabsTable.value[Number(currentTabIndex.value)].searchObj, ...obj };
    backStore.similarityObj.id = item.media_resource_id;
    getSimilar({
        id: item.media_resource_id,
        ...mergedObj,
        lastId: similarLastId
    }).then(res => {
    
        loadFlag.value = false;
        if (similarLastId == "") {
            initDataArr.value = [];
        }
        if (res.data.result.data.length >= 30) {
            similarLastId = res.data.result.page.last_id;
        };
        similarityFlag.value = true;
        initDataArr.value = [...initDataArr.value, ...res.data.result.data];
    }).catch(err => {
        loadFlag.value = false;
    });
};

// 相似处理
const rowClick = () => {
    if (similarityFlag.value) {
        similarLastId = '';
        similarityItem.value = '';
        similarityFlag.value = false;
        tabPosition.value = "all";
        tabsTable.value[Number(currentTabIndex.value)].searchObj["mainType"] = 0;
        if (searchText.value == '') {
            SuccessfuCallbackFn();
        } else {
            backSearchFn();
            rollToLoadFn();
        }

    }
};


// 还原
const handrestoreFn = (type: number, item: any) => {
    let postObj: senType = {
        location: 2,
    };
    let IdArr: any = [];
    if (type == 1) {
        if (item.type == 0) {
            postObj.folder_id = item.media_resource_id;
            delete postObj.file_id;
            delete postObj.files;
        } else {
            postObj.file_id = item.media_resource_id;
            delete postObj.folder_id;
            delete postObj.files;
        }
    } else if (type == 2) {
        item.map((i: any) => {
            IdArr.push(i.media_resource_id);
        });
        postObj.files = IdArr;
        delete postObj.file_id;
        delete postObj.folder_id;
    }
    request({
        url: "/mediaresource-manage-service/resource/recover",
        method: "put",
        data: postObj,
    }).then((res) => {
        message.success("还原成功");
        SuccessfuCallbackFn();
        getMedianRecycleCount();
    });
};

// 弹框
const cancelFn = (item: any) => {
    breadMoveCrumb.value = [{
        title: "全部",
        file_id: null,
    }];
    searchFolder.value = '';
    openFlag.value = false;
    useGlobal.setMoveDirectoryId(0);
};

const handleLastId = (data: any) => {
    (document.getElementById("admin-page") as any).scrollTop = 0;
    tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = data;
}

const handleText = (data: any) => {
    searchText.value = data;
    if (tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 101 || tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] == 102) {
        tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = 0;
        return;
    };
    if (searchText.value.length == 0) {
        tabsTable.value[Number(currentTabIndex.value)].searchObj['lastId'] = '';
        tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = null;
        noMoreData.value = false;
        if (tabsTable.value[Number(currentTabIndex.value)].searchObj['folder_id'] == 0) {
            initDataFn(1);
        } else {
            tabsTable.value[Number(currentTabIndex.value)].searchObj['lastId'] = '';
            initDataFn(currentTypeId.value);
        }
    }
    filterFlag.value = false;
}

const handleSearch = (data: any) => {
    if (!tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] || !searchText.value || searchTabStatus.value) {
        initDataArr.value = [];
        searchTabStatus.value = false;
    }
    if (data.length < pageItem.value) noMoreData.value = true;
    initDataArr.value = [...initDataArr.value, ...data];
    if (initDataArr.value.length == 0) {
        pageFlag.value = true;
    }
    // tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = 1;
    filterFlag.value = false;
    loadFlag.value = false;
};

const handleKeyWord = (data: any) => {
    if (!tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag']) {
        initDataArr.value = [];
    }
    initDataArr.value = [...initDataArr.value, ...data];
    if (initDataArr.value.length == 0) {
        tabsTable.value[Number(currentTabIndex.value)].searchObj['lastId'] = 0;
        pageFlag.value = true;
    }
    // tabsTable.value[Number(currentTabIndex.value)].searchObj['searchFlag'] = 1;
};
// 点击左侧栏目树
const selectTree = (selectedKeys: any, e: any) => {
    if (e.node.name == '全部标签') {
        router.push('/admin/mediaTag');
    } else if (e.node.name == '人物信息') {
        router.push('/admin/character');
    } 

    searchRef.value?.clearInput()
    // 如果不是文件夹tab，需要定位到全部
    if( tabPosition.value != 'folder'){
     tabPosition.value = 'all';
    }
    tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = "";
    tabsTable.value[Number(currentTabIndex.value)].searchObj["mainType"] = 0;
    breadCrumb.value = [{ title: "全部", file_id: null }];
    if (e.selected) {
        currentTypeId.value = {
            media_resource_id: e.node.id,
            ...e.node
        }
        useFileInfo.setDirectoryId( e.node.id);
        initDataFn({ media_resource_id: e.node.id })
        if (!e.parent) e.parent = e.node.parent
        const arrList = getBreadCrumbByTree(e, [])
        breadCrumb.value = breadCrumb.value.concat(arrList.reverse())
    } else {
        useFileInfo.setDirectoryId("0");
        initDataFn(1)
    }
}
// 递归树状结构获取面包屑
const getBreadCrumbByTree:any = (parent: any, arrlist: any) => {
    arrlist.push({
        title: parent.node.name,
        file_id: parent.node.id,
        main_type: 7,
        media_resource_id: parent.node.id,
    })
    if (parent?.parent) {
        return getBreadCrumbByTree(parent.parent, arrlist)
    } else {
        return arrlist
    }
}
// 设置树状选中高亮状态
const setSelectedKeys = (item?: any) => {
    sideTreeRef.value?.setSelectedKeys(item)
}
// 删除左侧树的时候，判断右侧面包屑和内容是否要更新
const handleTreeDelete = (item:any)=>{
    const _o = breadCrumb.value.find(v=>{
        return item.id == v.media_resource_id
    })
    if(_o){
        // 删除的文件面包屑中有的时候
        tabsTable.value[Number(currentTabIndex.value)].searchObj.lastId = "";
        breadCrumb.value = [{ title: "全部", file_id: null }];
        initDataFn(1)
    }else{
        //  过滤掉删除的数据
        initDataArr.value = initDataArr.value.filter(v=>{
        return v.media_resource_id !=item.id
        })
    }
}
// 移动左侧树时候，，判断右侧面包屑和内容是否要更新
const handleTreeMove = async (item:any) => {
    const _o = breadCrumb.value.find(v=>{
        return item.id == v.media_resource_id
    })
    // 联动了
    if(_o){
        backStore.netdiskObj.currentTypeId = {media_resource_id:item.id}
        await backStore.setBreadCrumbById()
        breadCrumb.value = backStore.netdiskObj.breadCrumb;
        initDataFn(backStore.netdiskObj.currentTypeId);
    }else{
        //  过滤掉移动掉的数据
        initDataArr.value = initDataArr.value.filter(v=>{
        return v.media_resource_id !=item.id
        })
    }
}

// 更新左侧树的重命名
const refreshTreeName = (item: any) => {
    sideTreeRef.value?.refreshTreeName(item)
}
// 更新左侧树的新增
const refreshTreAdd = (item: any) => {
    // sideTreeRef.value?.refreshTreAdd(item)
    resetTreeData()
}
// 更新左侧树的删除
const refreshDeleteData = (item: any) => {
    // sideTreeRef.value?.refreshDeleteData(item)
    resetTreeData()
}
// 更新左侧树的移动
const refreshTreeMoveData = (item: any) => {
    // sideTreeRef.value?.refreshTreeMoveData(item)
    resetTreeData()
}
// 一些批量操作的，触发左侧树全量更新，
const resetTreeData = () =>{
    sideTreeRef.value?.resetTreeData()
}
</script>
<style lang="scss" scoped src="./Index.scss"></style>
<style lang="scss" scoped src="@/assets/css/list.scss"></style>
